package com.xx.springboot.DataStructure.LeetCode.String;

import java.util.Arrays;

/**
 * Created by xiaoxiunique on 2018-8-22.
 */
public class longestCommonPrefix {
    public String longestCommonPrefix(String[] strs){
        if(strs == null || strs.length == 0)
            return "";

        if (strs.length == 1)
            return strs[0];
        Arrays.sort(strs);
        String lastTemplate = strs[0];

        int total = 0, count = 0;
        for (int i = 0 ; i < lastTemplate.length(); i ++) {
            for (int j = 0 ; j < strs.length ; j++) {
                if(strs[j].length() == 0)
                    return "";

                if (lastTemplate.charAt(i) == strs[j].charAt(i)) {
                    count ++;
                }
            }
            if (count == strs.length) {
                count = 0;
                total ++;
            }
            else
                break;
        }
        return lastTemplate.substring(0, total);
    }

    public static void main(String[] args) {
        String[] strs = {"casdf", "123c"};

        Arrays.sort(strs);

        System.out.println(Arrays.toString(strs));

        //(new longestCommonPrefix()).longestCommonPrefix(strs);
        //System.out.println((new longestCommonPrefix()).longestCommonPrefix(strs));
    }
}
